// pages/eulogy/index.ts

Page({
  data: {
    name: '111',
    avatar: 'https://via.placeholder.com/80',
    incenseCount: 99,
    deadOpenId: '',           // 逝者 openId
    commenterOpenId: '',      // 评论者 openId
    eulogies: [] as Array<any>,  // 悼词数组
    inputValue: '',
    disableSubmit: true,
    page: 1,
    pageSize: 10,
    loading: false,
    noMoreData: false,
    openId: '',
  },

  onLoad(options: Record<string, string>) {
    const app = getApp<IAppOption>();

    if (options) {
      this.setData({
        name: decodeURIComponent(options.name),
        avatar: decodeURIComponent(options.avatar),
        deadOpenId: decodeURIComponent(options.openId),
      });
    }

    const cachedOpenId = app.globalData.userId;

    if (cachedOpenId) {
      this.setData({ commenterOpenId: cachedOpenId , openId: cachedOpenId});
    }

    this.loadEulogies();
  },

  async loadEulogies() {
    if (this.data.loading || this.data.noMoreData) return;

    this.setData({ loading: true });

    try {
      const res: any = await wx.cloud.callFunction({
        name: 'eulogy_operate',
        data: {
          action: 'list',
          deadOpenId: this.data.deadOpenId,
          page: this.data.page,
          pageSize: this.data.pageSize,
        },
      });

      const newEulogies = res.result?.eulogies || [];

      this.setData({
        eulogies: [...this.data.eulogies, ...newEulogies],
        loading: false,
        noMoreData: newEulogies.length < this.data.pageSize,
        page: this.data.page + 1,
      });
    } catch (error) {
      console.error('加载悼词失败', error);
      this.setData({ loading: false });
      wx.showToast({ title: '加载失败', icon: 'none' });
    }
  },

  onReachBottom() {
    this.loadEulogies();
  },

  onIncenseTap() {
    this.setData({
      incenseCount: this.data.incenseCount + 1,
    });
    wx.showToast({
      title: '上香成功',
      icon: 'success',
    });
  },

  onInputChange(e: WechatMiniprogram.Input) {
    const val = e.detail.value;
    this.setData({
      inputValue: val,
      disableSubmit: !val.trim(),
    });
  },

  // 点赞事件
  async onLikeEulogyTap(e: WechatMiniprogram.TouchEvent) {
    const { id, likes } = e.currentTarget.dataset;
    if (!id) return;

    try {
      await wx.cloud.callFunction({
        name: 'eulogy_operate',
        data: {
          action: 'update',
          id,
          updateData: {
            likes: likes + 1,
          }
        }
      });

      // 点赞成功，本地同步更新
      const eulogies = this.data.eulogies.map(item => {
        if (item.id === id) {
          return { ...item, likes: item.likes + 1 };
        }
        return item;
      });

      this.setData({ eulogies });

    } catch (err) {
      console.error('点赞失败', err);
      wx.showToast({ title: '点赞失败', icon: 'none' });
    }
  },

  async onSubmitEulogy() {
    const content = this.data.inputValue.trim();
    if (!content) return;

    try {
      const res: any = await wx.cloud.callFunction({
        name: 'eulogy_operate',
        data: {
          action: 'add',
          deadOpenId: this.data.deadOpenId,
          commenterOpenId: this.data.commenterOpenId,
          content,
        },
      });

      if (res.result?.success) {
        wx.showToast({ title: '留言成功', icon: 'success' });

        this.setData({
          inputValue: '',
          disableSubmit: true,
          eulogies: [],
          page: 1,
          noMoreData: false,
        });

        this.loadEulogies();
      } else {
        wx.showToast({
          title: res.result?.message || '留言失败',
          icon: 'none',
        });
      }
    } catch (err) {
      console.error('留言失败', err);
      wx.showToast({
        title: '留言失败，请稍后再试',
        icon: 'none',
      });
    }
  },

  async onDeleteEulogyTap(e: WechatMiniprogram.TouchEvent) {
    const { id, commenterOpenId } = e.currentTarget.dataset;
    if (commenterOpenId !== this.data.commenterOpenId) {
      wx.showToast({ title: '只能删除自己的留言', icon: 'none' });
      return;
    }

    try {
      const res: any = await wx.cloud.callFunction({
        name: 'eulogy_operate',
        data: {
          action: 'delete',
          id,
        },
      });

      if (res.result?.success) {
        wx.showToast({ title: '删除成功', icon: 'success' });
        this.setData({
          eulogies: [],
          page: 1,
          noMoreData: false,
        });
        this.loadEulogies();
      } else {
        wx.showToast({
          title: res.result?.message || '删除失败',
          icon: 'none',
        });
      }
    } catch (err) {
      console.error('删除失败', err);
      wx.showToast({
        title: '删除失败，请稍后再试',
        icon: 'none',
      });
    }
  },
});
